package com.lipi.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lipi.common.utils.PageUtils;
import com.lipi.common.utils.Query;
import com.lipi.common.utils.R;
import com.lipi.mall.product.dao.SkuInfoDao;
import com.lipi.mall.product.entity.SkuImagesEntity;
import com.lipi.mall.product.entity.SkuInfoEntity;
import com.lipi.mall.product.entity.SpuInfoDescEntity;
import com.lipi.mall.product.feign.SeckillFeignService;
import com.lipi.mall.product.service.*;
import com.lipi.mall.product.vo.SeckillInfoVO;
import com.lipi.mall.product.vo.SkuItemSaleAttrsVO;
import com.lipi.mall.product.vo.SkuItemVO;
import com.lipi.mall.product.vo.SpuItemAttrGroupVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SeckillFeignService seckillFeignService;


    @Autowired
    ThreadPoolExecutor executor;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * key
         * catelogId
         * brandId
         * min
         * max
         */
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !catelogId.equalsIgnoreCase("0")) {
            wrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !brandId.equalsIgnoreCase("0")) {
            wrapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (StringUtils.isNotEmpty(min)) {
            wrapper.ge("price", min);
        }

        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal(0)) == 1) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {
            }
        }


        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntityList = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntityList;
    }


    @Override
    public SkuItemVO item(Long skuId) throws ExecutionException, InterruptedException {

        SkuItemVO result = new SkuItemVO();


        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync((
        ) -> {//1、sku基本数据获取 pms_sku_info
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            result.setInfo(skuInfoEntity);
            return skuInfoEntity;

        }, executor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            Long spuId = res.getSpuId();

            //3、sku所属spu的所有销售属性
            List<SkuItemSaleAttrsVO> saleAttrsVOList = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
            result.setSaleAttrs(saleAttrsVOList);

        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            Long spuId = res.getSpuId();

            //4、spu的介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getOne(new QueryWrapper<SpuInfoDescEntity>().eq("spu_id", spuId));
            result.setDesc(spuInfoDescEntity);

        }, executor);


        CompletableFuture<Void> groupAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            Long spuId = res.getSpuId();
            Long catalogId = res.getCatalogId();

            //5、规格参数信息
            List<SpuItemAttrGroupVO> attrGroupWithAttrsBySpuId = attrGroupService.getAttrGroupWithAttrsBySpuId(spuId, catalogId);
            result.setGroupAttrs(attrGroupWithAttrsBySpuId);

        }, executor);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            //2、sku图片获取 pms_sku_images
            List<SkuImagesEntity> skuImagesEntityList = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            result.setImages(skuImagesEntityList);
        }, executor);

        //查询商品在三天内是否有秒杀信息
        CompletableFuture<Void> seckillTask = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.skuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillInfoVO data = r.getData(new TypeReference<SeckillInfoVO>() {
                });
                result.setSeckillInfoVO(data);
            }

        }, executor);

        //等待所有任务执行完成
        CompletableFuture.allOf(saleAttrFuture, groupAttrFuture, descFuture, imagesFuture, seckillTask).get();

        return result;
    }

    @Override
    public BigDecimal getPriceById(Long skuId) {
        return this.getById(skuId).getPrice();
    }


}